package com.le.dub.controller;

import cn.hutool.core.util.PhoneUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.le.dub.common.BusinessRuntimeException;
import com.le.dub.common.Response;
import com.le.dub.mobile.User;
import com.le.dub.mobile.bo.UserRegisterBO;
import com.le.dub.service.IUserService;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

/**
 * 用户相关接口
 *
 * @author guole
 * @created 2024/11/15
 */
@RestController
@RequestMapping("/app/user")
public class AppUserController {
    @Resource
    private IUserService userService;

    /**
     * 注册
     *
     * @return
     */
    @PostMapping("/register")
    Response register(UserRegisterBO userRegisterBO) {
        if(!PhoneUtil.isMobile(userRegisterBO.getPhone())){
            throw new BusinessRuntimeException("500", "不是有效的手机号，请重新输入");
        }
       Integer count= userService.lambdaQuery().eq(User::getPhone,userRegisterBO.getPhone()).count();
        if(count>0){
            throw new BusinessRuntimeException("500", "手机号已注册");
        }
      String token=  userService.register(userRegisterBO);

        return Response.success(token);
    }

    /**
     * 登录
     *
     * @return
     */
    @PostMapping("/login")
    Response login(@RequestBody  UserRegisterBO userRegisterBO ) {

        String  token=this.userService.login(userRegisterBO.getPhone(),userRegisterBO.getPassword());
        return Response.success(token);
    }

    /**
     * 发送验证码
     *
     * @param phone 手机号
     * @return type 验证码类型(1注册 2登录)
     */
    @GetMapping("/sendCaptcha")
    public Response sendCaptcha(@RequestParam("phone") String phone,@RequestParam("type") Integer type) {
        userService.sendCaptcha(phone,type);
        return Response.success();
    }
}
